<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'pid', 'status'
    ];


    // 定义父分类关系
    public function parent()
    {
        return $this->belongsTo(Category::class, 'pid');
    }

    // 定义子分类关系
    public function children()
    {
        return $this->hasMany(Category::class, 'pid');
    }

    public static function selectOptions()
    {
        $categories = static::with('children')->get()->toArray();

        $options = [];
        self::buildOptions($categories, $options);

        return $options;
    }

    protected static function buildOptions($categories, &$options, $prefix = '')
    {
        foreach ($categories as $category) {
            $options[$category['id']] = $prefix . ' ' . $category['title'];

            if (!empty($category['children'])) {
                self::buildOptions($category['children'], $options, $prefix . '--');
            }
        }
    }


    public static function getSecondLevel()
    {
        return self::query()->where('pid', '>', 0)->select('id', 'title')->pluck('title', 'id');
    }

    public static function getFirstLevel()
    {
        return self::query()->where('pid', '=', 0)->select('id', 'title')->pluck('title', 'id');
    }

    public function getCategoryTree($parentId = 0)
    {
        // 获取顶级分类
        $categories = Category::where('pid', $parentId)->get();

        $tree = [];

        foreach ($categories as $category) {
            // 构建当前分类节点
            $node = [
                'id' => $category->id,
                'title' => $category->title,
                'children' => $this->getCategoryTree($category->id), // 递归获取子分类
                'desc' => $category->desc
            ];

            $tree[] = $node;
        }

        return $tree;
    }
}
